<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多租户订单数据生成器</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">

    <style>
        .container {
            margin-top: 20px;
        }
        .panel {
            border: 1px solid #ddd;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .panel-header {
            padding: 15px;
            background-color: #f5f5f5;
            border-bottom: 1px solid #ddd;
            border-radius: 5px 5px 0 0;
            font-weight: bold;
            font-size: 16px;
        }
        .panel-body {
            padding: 15px;
        }
        .log-container {
            height: 500px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            background-color: #f9f9f9;
            font-family: monospace;
            font-size: 14px;
        }
        .log-item {
            margin-bottom: 5px;
            padding: 3px 0;
            border-bottom: 1px dashed #eee;
        }
        .log-item:last-child {
            border-bottom: none;
        }
        .btn-generate {
            width: 100%;
            padding: 10px;
            font-size: 16px;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0,0,0,.3);
            border-radius: 50%;
            border-top-color: #007bff;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .form-group {
            margin-bottom: 15px;
        }

        /* 年月选择器样式 */
        .year-month-picker-trigger {
            width: 100%;
            border: 1px solid #ced4da;
            border-radius: 0.25rem;
            padding: 0.375rem 0.75rem;
            cursor: pointer;
            background-color: white;
        }
        .year-month-picker-trigger:hover {
            border-color: #86b7fe;
        }
        .year-month-container {
            display: none;
            position: absolute;
            background-color: white;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            z-index: 1000;
            width: 350px;
        }
        .year-month-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #ddd;
        }
        .year-month-nav-btn {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1.2rem;
            color: #0d6efd;
        }
        .year-display {
            font-weight: bold;
            font-size: 1.1rem;
        }
        .months-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 5px;
            padding: 10px;
        }
        .month-item {
            padding: 10px;
            text-align: center;
            cursor: pointer;
            border: 1px solid transparent;
            border-radius: 4px;
        }
        .month-item:hover:not(.disabled) {
            background-color: #e9f5ff;
            border-color: #bed7fe;
        }
        .month-item.selected {
            background-color: #0d6efd;
            color: white;
        }
        .month-item.disabled {
            color: #ccc;
            cursor: not-allowed;
        }
        .month-item.current {
            font-weight: bold;
            border: 1px solid #0d6efd;
        }
        .selected-months-container {
            margin-top: 10px;
        }
        .selected-month-tag {
            display: inline-block;
            background-color: #e9f5ff;
            color: #0d6efd;
            padding: 3px 8px;
            border-radius: 12px;
            margin: 0 5px 5px 0;
            font-size: 0.8rem;
        }
        .remove-month {
            margin-left: 5px;
            cursor: pointer;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div class="container">
    <h1 class="text-center mb-4">多租户订单数据生成器</h1>

    <div class="row">
        <!-- 左侧表单 -->
        <div class="col-md-6">
            <div class="panel">
                <div class="panel-header">
                    <i class="fa fa-cogs"></i> 生成配置
                </div>
                <div class="panel-body">
                    <form id="generateForm">
                        <div class="form-group">
                            <label for="yearMonthPickerTrigger">选择年月:</label>
                            <!-- 年月选择器触发器 -->
                            <div id="yearMonthPickerTrigger" class="year-month-picker-trigger d-flex justify-content-between align-items-center">
                                <span id="selectedMonthsText">请选择年月...</span>
                                <i class="fa fa-calendar text-primary"></i>
                            </div>

                            <!-- 已选年月展示 -->
                            <div id="selectedMonthsContainer" class="selected-months-container mt-2 d-none">
                                <div id="selectedMonthsList"></div>
                            </div>

                            <!-- 年月选择容器 -->
                            <div id="yearMonthContainer" class="year-month-container mt-2">
                                <!-- 年月头部 -->
                                <div class="year-month-header">
                                    <button type="button" id="prevYear" class="year-month-nav-btn">
                                        <i class="fa fa-chevron-left"></i>
                                    </button>
                                    <div class="year-display" id="currentYearDisplay"></div>
                                    <button type="button" id="nextYear" class="year-month-nav-btn">
                                        <i class="fa fa-chevron-right"></i>
                                    </button>
                                </div>

                                <!-- 月份网格 -->
                                <div id="monthsGrid" class="months-grid">
                                    <!-- 月份会动态生成 -->
                                </div>
                            </div>

                            <input type="hidden" id="selectedMonths" name="selectedMonths" required>
                            <small class="form-text text-muted">点击月份进行选择/取消，可选择多个年月</small>
                        </div>

                        <div class="form-group">
                            <label for="bigTenantPercentage">大租户占比 (%):</label>
                            <input type="number" id="bigTenantPercentage" name="bigTenantPercentage"
                                   class="form-control" min="0" max="100" value="30" required>
                        </div>

                        <div class="form-group">
                            <label for="tenantCount">生成租户数量:</label>
                            <input type="number" id="tenantCount" name="tenantCount"
                                   class="form-control" min="1" value="10" required>
                        </div>

                        <div class="form-group">
                            <label for="monthlyDataVolume">每月数据量 (万条):</label>
                            <input type="number" id="monthlyDataVolume" name="monthlyDataVolume"
                                   class="form-control" min="1" value="1000" required>
                        </div>

                        <button type="submit" id="generateBtn" class="btn btn-primary btn-generate">
                            <i class="fa fa-play"></i> 开始生成数据
                        </button>
                        <button type="button" id="clearLogBtn" class="btn btn-secondary btn-generate mt-2">
                            <i class="fa fa-trash"></i> 清空日志
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- 右侧日志 -->
        <div class="col-md-6">
            <div class="panel">
                <div class="panel-header">
                    <i class="fa fa-list-alt"></i> 生成日志
                    <span id="generatingIndicator" class="float-end text-danger" style="display: none;">
                            <span class="loading"></span> 正在生成中...
                        </span>
                </div>
                <div class="panel-body">
                    <div id="logContainer" class="log-container">
                        <!-- 日志内容将通过JS动态加载 -->
                        <div class="log-item text-info">等待开始生成数据...</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 轮询间隔 (毫秒)
    const POLL_INTERVAL = 2000;
    // 日志轮询定时器
    let logPollTimer = null;

    // 年月选择器相关变量
    let currentYear = new Date().getFullYear();
    let selectedMonths = new Set(); // 存储格式: YYYY-MM

    $(document).ready(function() {
        // 初始化年月选择器
        initYearMonthPicker();

        // 初始化页面
        checkGeneratingStatus();

        // 开始日志轮询
        startLogPolling();

        // 生成表单提交
        $('#generateForm').submit(function(e) {
            e.preventDefault();

            // 检查是否选择了年月
            if (selectedMonths.size === 0) {
                alert('请至少选择一个年月！');
                return;
            }

            // 检查是否正在生成
            if ($('#generatingIndicator').is(':visible')) {
                alert('数据生成已在进行中，请不要重复提交！');
                return;
            }

            // 获取表单数据
            const formData = {
                months: Array.from(selectedMonths),
                bigTenantPercentage: parseInt($('#bigTenantPercentage').val()),
                tenantCount: parseInt($('#tenantCount').val()),
                monthlyDataVolume: parseInt($('#monthlyDataVolume').val())
            };

            // 禁用按钮
            $('#generateBtn').prop('disabled', true).html(
                '<span class="loading"></span> 正在启动...'
            );

            // 发送请求
            $.ajax({
                url: '/generate',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    if (response.success) {
                        showLog(response.message);
                        $('#generatingIndicator').show();
                    } else {
                        alert(response.message);
                    }
                    $('#generateBtn').prop('disabled', false).html(
                        '<i class="fa fa-play"></i> 开始生成数据'
                    );
                },
                error: function(xhr) {
                    alert('请求失败: ' + xhr.responseText);
                    $('#generateBtn').prop('disabled', false).html(
                        '<i class="fa fa-play"></i> 开始生成数据'
                    );
                }
            });
        });

        // 清空日志按钮
        $('#clearLogBtn').click(function() {
            if (confirm('确定要清空日志吗？')) {
                $.post('/clearLogs', function(response) {
                    if (response.success) {
                        $('#logContainer').empty();
                        showLog('日志已清空');
                    } else {
                        alert(response.message);
                    }
                });
            }
        });
    });

    // 初始化年月选择器
    function initYearMonthPicker() {
        // 渲染月份
        renderMonths(currentYear);

        // 切换选择器显示/隐藏
        $('#yearMonthPickerTrigger').click(function(e) {
            e.stopPropagation();
            $('#yearMonthContainer').toggle();
        });

        // 点击页面其他地方关闭选择器
        $(document).click(function(e) {
            if (!$(e.target).closest('#yearMonthContainer, #yearMonthPickerTrigger').length) {
                $('#yearMonthContainer').hide();
            }
        });

        // 上一年
        $('#prevYear').click(function() {
            currentYear--;
            renderMonths(currentYear);
        });

        // 下一年
        $('#nextYear').click(function() {
            currentYear++;
            renderMonths(currentYear);
        });
    }

    // 渲染月份
    function renderMonths(year) {
        // 更新年份显示
        $('#currentYearDisplay').text(`${year}年`);

        // 清空月份网格
        $('#monthsGrid').empty();

        // 获取当前年月
        const today = new Date();
        const currentMonth = today.getMonth() + 1; // 1-12
        const isCurrentYear = today.getFullYear() === year;

        // 月份名称
        const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月',
            '七月', '八月', '九月', '十月', '十一月', '十二月'];

        // 添加12个月份
        for (let month = 1; month <= 12; month++) {
            const monthStr = `${year}-${String(month).padStart(2, '0')}`;
            const monthEl = $(`<div class="month-item"></div>`).text(monthNames[month - 1]);

            // 标记当前月份
            if (isCurrentYear && month === currentMonth) {
                monthEl.addClass('current');
            }

            // 标记已选择的月份
            if (selectedMonths.has(monthStr)) {
                monthEl.addClass('selected');
            }

            // 添加点击事件
            monthEl.click(function() {
                if (selectedMonths.has(monthStr)) {
                    selectedMonths.delete(monthStr);
                    monthEl.removeClass('selected');
                } else {
                    selectedMonths.add(monthStr);
                    monthEl.addClass('selected');
                }
                updateSelectedMonthsDisplay();
            });

            $('#monthsGrid').append(monthEl);
        }
    }

    // 更新已选年月显示
    function updateSelectedMonthsDisplay() {
        // 更新文本显示
        if (selectedMonths.size === 0) {
            $('#selectedMonthsText').text('请选择年月...');
            $('#selectedMonthsContainer').addClass('d-none');
            $('#selectedMonths').val('');
        } else {
            $('#selectedMonthsText').text(`${selectedMonths.size} 个年月已选择`);
            $('#selectedMonthsContainer').removeClass('d-none');

            // 清空现有标签
            $('#selectedMonthsList').empty();

            // 排序年月
            const sortedMonths = Array.from(selectedMonths).sort();

            // 添加新标签
            sortedMonths.forEach(monthStr => {
                const [year, month] = monthStr.split('-');
                const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'];
                const monthName = monthNames[parseInt(month) - 1];

                const monthTag = $(`<div class="selected-month-tag">${year}年${monthName} <span class="remove-month" data-month="${monthStr}">×</span></div>`);
                $('#selectedMonthsList').append(monthTag);

                // 添加删除单个年月的事件
                monthTag.find('.remove-month').click(function(e) {
                    e.stopPropagation();
                    const monthToRemove = $(this).data('month');
                    selectedMonths.delete(monthToRemove);
                    updateSelectedMonthsDisplay();
                    renderMonths(currentYear);
                });
            });

            // 更新隐藏字段的值
            $('#selectedMonths').val(sortedMonths.join(','));
        }
    }

    // 检查生成状态
    function checkGeneratingStatus() {
        $.get('/logs', function(response) {
            if (response.isGenerating) {
                $('#generatingIndicator').show();
                $('#generateBtn').prop('disabled', true);
            } else {
                $('#generatingIndicator').hide();
                $('#generateBtn').prop('disabled', false);
            }
        });
    }

    // 开始日志轮询
    function startLogPolling() {
        // 清除现有定时器
        if (logPollTimer) {
            clearInterval(logPollTimer);
        }

        // 立即获取一次日志
        fetchLogs();

        // 设置定时器
        logPollTimer = setInterval(fetchLogs, POLL_INTERVAL);
    }

    // 获取日志
    function fetchLogs() {
        $.get('/logs', {count: 100}, function(response) {
            // 更新生成状态
            if (response.isGenerating) {
                $('#generatingIndicator').show();
                $('#generateBtn').prop('disabled', true);
            } else {
                $('#generatingIndicator').hide();
                $('#generateBtn').prop('disabled', false);
            }

            // 更新日志内容
            updateLogs(response.logs);
        });
    }

    // 更新日志显示
    function updateLogs(logs) {
        const logContainer = $('#logContainer');
        logContainer.empty();

        if (logs && logs.length > 0) {
            logs.forEach(function(log) {
                showLog(log);
            });
        } else {
            showLog('暂无日志信息');
        }
    }

    // 显示单条日志
    function showLog(message) {
        const logContainer = $('#logContainer');
        const logItem = $('<div class="log-item"></div>').text(message);

        // 根据日志内容添加样式
        if (message.includes('失败')) {
            logItem.addClass('text-danger');
        } else if (message.includes('完成')) {
            logItem.addClass('text-success');
        } else if (message.includes('开始')) {
            logItem.addClass('text-primary');
        }

        logContainer.append(logItem);
        // 滚动到底部
        logContainer.scrollTop(logContainer[0].scrollHeight);
    }
</script>
</body>
</html>
